﻿using log4net;
using Nova_BLL;
using Nova_Common;
using Nova_Common.Extend;
using Nova_MOD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WMS_Api.App_Start;
using WMS_Api.Areas.MesSystem.Models;
using WMS_Api.Controllers;
using WMS_Api.Models;

namespace WMS_Api.Areas.MesSystem.Controllers
{
    /// <summary>
    /// 收料单
    /// </summary>
    [RoutePrefix("api/MesSystem/MaterialReceive")]
    public class MaterialReceiveController : BaseMesApiController
    {
        TBill_AddStorageBll addStorageBll = new TBill_AddStorageBll();
        TAddStorage_ListBll addStorageListBll = new TAddStorage_ListBll();
        TBase_MaterialBll materialBll = new TBase_MaterialBll();
        TBase_InterfaceBll interfaceBll = new TBase_InterfaceBll();
        ILog _logger = log4net.LogManager.GetLogger(typeof(MaterialReceiveController));

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PushInfo")]
        [ValidateModel]
        [MesWebApiExceptionFilter]
        public MesApiResult PushInfo(MesMaterialReceiveExtendModel param)
        {
            if (param.IsEmpty())
                return Error("收料单参数不能为空!");
            _logger.InfoFormat("MES 推送收料单信息，参数:{0}", param.ToJson());
            if (param.data.IsEmpty())
                return Error("收料单data参数不能为空!");
            if (param.type == 0)
                return Insert(param.data.FirstOrDefault());
            else if(param.type == 1)
                return Update(param.data.FirstOrDefault());
            else if(param.type == 2)
                return Delete(param.data.FirstOrDefault());
            else
                return Error("参数type只能为(0,1,2)!");
        }

        private MesApiResult Insert(MesMaterialReceiveModel matReceive)
        {
            if (matReceive.IsEmpty())
                return Error("收料单传递的参数为空!");
            var addStorageModel = addStorageBll.GetByStockNo(matReceive.mr_no);
            if (!addStorageModel.IsEmpty())
                return Error(string.Format("收料单号:{0}已经存在库中，无法新增!", matReceive.mr_no));
            var addStorageListModel = addStorageListBll.GetByStockNo(matReceive.mr_no);
            if (!addStorageListModel.IsEmpty())
                return Error("收料单中的明细信息已经存在库中，无法新增!");
            var materialModel = materialBll.GetByMatCode(matReceive.part_no);
            if (materialModel.IsEmpty())
                return Error(string.Format("收料单中的物料编码:{0}不存在库中，无法新增收料单信息!", matReceive.part_no));
            DateTime date = DateExtend.GetTime(matReceive.create_time, true);
            TBill_AddStorage addStorageEntity = new TBill_AddStorage();
            addStorageEntity.PID = Guid.NewGuid().ToString().ToUpper();
            addStorageEntity.StockNo = matReceive.mr_no;
            addStorageEntity.Small_BillType = "11";
            addStorageEntity.Bill_Status = 0;
            addStorageEntity.Async_Status = 0;
            addStorageEntity.S03 = matReceive.vendor_no;
            addStorageEntity.S04 = matReceive.vendor_name;
            addStorageEntity.B01 = 1; // 1：代表MES创建
            addStorageEntity.OID = "MES";
            addStorageEntity.CDT = date;
            TAddStorage_List addStorageListEntity = new TAddStorage_List();
            addStorageListEntity.StockNo = matReceive.mr_no;
            addStorageListEntity.Mat_Code = matReceive.part_no;
            addStorageListEntity.S05 = matReceive.po_no;
            addStorageListEntity.TS01 = string.IsNullOrWhiteSpace(matReceive.notice_no) ? "" : matReceive.notice_no;
            addStorageListEntity.Num = matReceive.quantity;
            addStorageListEntity.CDT = date;
            string setMatId = interfaceBll.GetSecMatId(addStorageListEntity.Mat_Code, addStorageListEntity.TS01);
            addStorageListEntity.Sec_Mat_ID = long.Parse(setMatId);
            bool isInsert = addStorageBll.InsertEntity(addStorageEntity, addStorageListEntity);
            return isInsert ? Success() : Error("新增收料单失败!");
        }

        private MesApiResult Update(MesMaterialReceiveModel matReceive)
        {
            if (matReceive.IsEmpty())
                return Error("收料单传递的参数为空!");
            var addStorageModel = addStorageBll.GetByStockNo(matReceive.mr_no);
            if (addStorageModel.IsEmpty())
                return Error(string.Format("收料单号:{0}不存在库中，无法修改!", matReceive.mr_no));
            var addStorageListModel = addStorageListBll.GetByStockNo(matReceive.mr_no);
            if (addStorageListModel.IsEmpty())
                return Error("收料单中的明细信息不存在库中，无法修改!");
            if (addStorageListModel.Act_Num > 0)
                return Error("此收料单已经有物料组盘入库，已无法修改此收料单!");
            DateTime date = DateExtend.GetTime(matReceive.create_time, true);
            addStorageListModel.Num = matReceive.quantity;
            addStorageListModel.S05 = matReceive.po_no;
            addStorageListModel.TS01 = matReceive.notice_no;
            addStorageListModel.CDT = date;
            string setMatId = interfaceBll.GetSecMatId(addStorageListModel.Mat_Code, addStorageListModel.TS01);
            addStorageListModel.Sec_Mat_ID = long.Parse(setMatId);
            bool isUpdate = addStorageListBll.UpdateEntity(addStorageListModel);
            return isUpdate ? Success() : Error("修改收料单失败!");
        }

        private MesApiResult Delete(MesMaterialReceiveModel matReceive)
        {
            var addStorageListModel = addStorageListBll.GetByStockNo(matReceive.mr_no);
            if(addStorageListModel.IsEmpty())
                return Error("收料单中的明细信息不存在库中，无法删除!");
            if(addStorageListModel.Act_Num !=0)
                return Error("收料单中的物料已经在PDA组盘，无法再删除!");
            var addStorageModel = addStorageBll.GetByStockNo(matReceive.mr_no);
            bool isDel = addStorageBll.DeleteEntity(addStorageModel, addStorageListModel);
            return isDel ? Success() : Error("删除收料单失败!");
        }
    }
}
